import axios from "axios";
import Nprogress from 'nprogress';
import {getUserTempId} from "@/utils";
import {Message} from "element-ui";
import store from "@/store";
import router from "@/router";
const yumaRequest = axios.create({
    baseURL:"/api",
    timeout:5000,
    params:{}
});
// 请求拦截
yumaRequest.interceptors.request.use(config=>{
    Nprogress.start();
    // config.params = config.params || {};
    config.params.k = Date.now();
    if(localStorage.getItem('token')){
        config.headers.token = localStorage.getItem('token');
    }
    config.headers.userTempId = getUserTempId();
    return config;
});
// 响应拦截
yumaRequest.interceptors.response.use(response=>{
    Nprogress.done();

    if(response.data.ok === -1){
        Message.error(response.data.message);
        return Promise.reject(response.data);
    }else if(response.data.ok === -2){
        Message.error(response.data.message+'请跳转到登录页面重新登录');
        store.commit('user/SET_USER_INFO');
        router.push({
            path:"/login",
            query:{
                returnUrl:router.currentRoute.fullPath
            }
        });
        //跳转至登录
        return new Promise(()=>{});
    }
    return response.data;
},reason=>{
    Nprogress.done();
    alert(reason);
    //如果响应有问题, 则中断promise链
    return new Promise(()=>{});
});
export default yumaRequest;